package com.wang.interview.threads;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: wang
 * @date: 2021/7/22 21:52
 * @description:
 */
public class Tester {

    private static int num;

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition1 = lock.newCondition();
    static Condition condition2 = lock.newCondition();

    public static void add() throws InterruptedException {
        lock.lock();
        while ( num == 1){
            condition1.await();
        }
        num ++;
        System.out.println("num += "+num);
        condition2.signal();
        lock.unlock();
    }

    public void sub() throws InterruptedException {
        lock.lock();
        while ( num == 0 ){
            condition2.await();
        }
        num --;
        System.out.println("num -= "+num);
        condition1.signal();
        lock.unlock();
    }

    public static void main(String[] args) {
        Tester tester = new Tester();
        new Thread(()->{try { while(true){tester.add();} } catch (InterruptedException e) { e.printStackTrace(); } },"A").start();
        new Thread(()->{try { while(true){tester.sub();} } catch (InterruptedException e) {e.printStackTrace(); } },"B").start();

    }

}


